package com.vichat.common.rudp.thread;

import com.vichat.common.rudp.RudpDataUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.util.concurrent.*;


public class RudpNioReceiveManager extends Thread {
    private static transient Logger logger = LoggerFactory.getLogger(RudpNioReceiveManager.class);
    public ExecutorService receivExec;

    public RudpNioReceiveManager() {
        BlockingQueue recvqueue = new ArrayBlockingQueue(800);
        receivExec = new ThreadPoolExecutor(100, 200, 10, TimeUnit.MINUTES, recvqueue, new ThreadPoolExecutor.DiscardPolicy());
        //receivExec = Executors.newFixedThreadPool(50);
    }

    public void run() {

        while (true) {
            try {
                long startIme = System.currentTimeMillis();
                //byte[] buffer = new byte[1024]; // 缓冲区  
                //DatagramPacket packet = new DatagramPacket(buffer, buffer.length);  
                long midtime = System.currentTimeMillis() - startIme;
                SocketAddress srcAddress = null;
                ByteBuffer buffer = ByteBuffer.allocate(1024);
                try {

                    srcAddress = RudpDataUtil.getServerSocketNio().receive(buffer);


                } catch (Exception e) {
                    logger.error("报文接收失败", e);
                    continue;
                }

                if (srcAddress != null) {
                    receivExec.execute(new RudpNioReceiveThread(srcAddress, buffer));

                    long costtime = System.currentTimeMillis() - startIme;
                    if (costtime > 10) {
                        logger.error("!!!!!!!!!!!!接收数据出错:" + costtime + "," + midtime + ":" + srcAddress.toString());
                    }

                } else {
                    sleep(50);
                }


                //logger.error("数据接收成功"+packet.getAddress().getHostAddress()+":"+packet.getPort()+";"+packet.getLength()+";"+new String(packet.getData()));


            } catch (Exception e) {
                logger.error("单个报文处理失败", e);
            }
        }

    }

}
